package com.bupt.leetcode;

/**
 * 字符串处理
 * 
 * @author Administrator
 * 
 */
public class StringProblem {
	/**
	 * URL： count and say
	 * 
	 * @param n
	 * @return
	 */
	public String countAndSay(int n) {
		if (n <= 0)
			return "";
		String pre = "1";
		for (int i = 1; i <= n; i++) {
			StringBuilder sb = new StringBuilder();
			int count = 1;
			for (int j = 1; j < pre.length(); j++) {
				if (pre.charAt(j) == pre.charAt(j - 1)) {
					count++;
				} else {
					sb.append(count);
					sb.append(pre.charAt(j - 1));
					count = 1;
				}
			}
			sb.append(count);
			sb.append(pre.length() - 1);
			pre = sb.toString();
		}
		return pre;
	}

	/**
	 * atoi
	 * 字符串转整形
	 * utl :https://leetcode.com/problems/string-to-integer-atoi/
	 * @param str
	 * @return
	 */
	public int myAtoi(String str) {
		if (str == null || str.length() == 0)
			return 0;
		int limit, flag = 1, result = 0, i = 0;
		while (str.charAt(i) == ' ')
			i++;
		if (str.charAt(i) == '-') {
			flag = -1;
			i++;
		} else if (str.charAt(i) == '+') {
			flag = 1;
			i++;
		}
		limit = (int) (Math.pow(2, 32) - 1);
		while (i < str.length()) {
			if (str.charAt(i) < '0' || str.charAt(i) > '9')
				break;
			int b = str.charAt(i) - '0';
			if (flag == 1 && (limit - b) / 10 < result)
				return limit;
			if (flag == -1
					&& (b == 0 && (limit / 10 + 0.1 < result) || (b != 0 && (limit + 1 - b) / 10 < result))) {
				return -1 * limit - 1;
			}
			result = result * 10 + b;
			i++;
		}
		return result * flag;
	}

	public int lengthOfLastWord(String s) {
		if (s.length() < 1)
			return 0;
		int k = s.length() - 1;
		while (k >= 0 && s.charAt(k) == ' ')
			k--;
		if (k == 0)
			return 0;
		while (k >= 0 && s.charAt(k) != ' ')
			k--;
		return s.length() - 1 - k;
	}
}
